/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-02-27     GXF       the first version
 */

#include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <u8g2_port.h>

// You may reference Drivers/drv_gpio.c for pinout
// In u8x8.h #define U8X8_USE_PINS

#define OLED_SPI_PIN_RES                     42  // PE11
#define OLED_SPI_PIN_DC                      41  // PE10
#define OLED_SPI_PIN_CS                      37  // PB2

static void LCD_thread(void *arg)
{
    u8g2_t u8g2;

    // Initialization
    u8g2_Setup_pcd8544_84x48_f( &u8g2, U8G2_R0, u8x8_byte_rtthread_4wire_hw_spi, u8x8_gpio_and_delay_rtthread);
    u8x8_SetPin(u8g2_GetU8x8(&u8g2), U8X8_PIN_CS, OLED_SPI_PIN_CS);
    u8x8_SetPin(u8g2_GetU8x8(&u8g2), U8X8_PIN_DC, OLED_SPI_PIN_DC);
    u8x8_SetPin(u8g2_GetU8x8(&u8g2), U8X8_PIN_RESET, OLED_SPI_PIN_RES);

    u8g2_InitDisplay(&u8g2);
    u8g2_SetPowerSave(&u8g2, 0);

    // Draw Graphics
    /* full buffer example, setup procedure ends in _f */
    u8g2_ClearBuffer(&u8g2);
    u8g2_SetFont(&u8g2, u8g2_font_wqy12_t_gb2312);
    u8g2_DrawStr(&u8g2, 1, 18, "U8g2 on RT-Thread");
    u8g2_SendBuffer(&u8g2);

    u8g2_SetFont(&u8g2, u8g2_font_wqy12_t_gb2312);
    u8g2_DrawGlyph(&u8g2, 112, 56, 0x2603 );
    u8g2_DrawStr(&u8g2, 0, 36, "U8g2 on RT-Thread");
    u8g2_SendBuffer(&u8g2);

    rt_kprintf("U8g2 on RT-Thread Display");
    while(1)
    {
        rt_thread_mdelay(500);
    }
}
//MSH_CMD_EXPORT(u8g2_ssd1306_12864_4wire_hw_spi_example, hardware 4 wire spi ssd1306 sample);

int u8g2_PCD8544_84X48_4wire_hw_spi_init(void)
{
    rt_thread_t tid = RT_NULL;

    /* Create background ticks thread */
    tid = rt_thread_create("lcd_5110", LCD_thread, RT_NULL, 1024, 26, 10);
    if(tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }

    return 0;
}
INIT_APP_EXPORT(u8g2_PCD8544_84X48_4wire_hw_spi_init);
